package com.mill.scala

import java.io.{OutputStream, ByteArrayOutputStream}
import java.nio.charset.Charset


import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.mybatis.spring.annotation.MapperScan
import org.springframework.context.annotation.Bean
import org.springframework.http.{HttpHeaders, MediaType, HttpOutputMessage}
import com.alibaba.fastjson.serializer.SerializerFeature
import com.alibaba.fastjson.support.config.FastJsonConfig
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.http.HttpMessageConverters

@SpringBootApplication
@MapperScan(value=Array("com.mill.scala.mapper"))
class AppConfig {

  /**
    * 使用fastJSON处理@ResposeBody
    *
    * @return
    */
  @Bean
  def fastjsonHttpMessageConverter:HttpMessageConverters={
    // 定义一个转换消息的对象
    val fastConverter = new MyHttpMessageConverter()
    // 添加fastjson的配置信息 比如 ：是否要格式化返回的json数据
    val fastJsonConfig = new FastJsonConfig()
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat)
    fastJsonConfig.setCharset(Charset.forName("utf-8"))
    // 在转换器中添加配置信息
    fastConverter.setFastJsonConfig(fastJsonConfig)
    val converter = fastConverter
    new HttpMessageConverters(converter)
  }
}

/**
  * fastJson对scala对象对写出存在一些问题
  * 这里使用json4s重写了序列化代码
  */
class MyHttpMessageConverter extends  FastJsonHttpMessageConverter{

  override def writeInternal(obj: AnyRef, outputMessage: HttpOutputMessage): Unit ={
    implicit val formats = Serialization.formats(NoTypeHints)
    val str = Serialization.write(obj)
    val headers: HttpHeaders = outputMessage.getHeaders
    val outnew: ByteArrayOutputStream = new ByteArrayOutputStream
    outnew.write(str.getBytes)
    headers.setContentLength(str.getBytes.length)
    val out: OutputStream = outputMessage.getBody
    outnew.writeTo(out)
    outnew.close

  }
}

object ScalaSpringBootApplication extends App{
  SpringApplication.run(classOf[AppConfig])
}